#!/usr/bin/env python

import os, re, shlex
from Tkinter import *
from tkSimpleDialog import Dialog
import tkColorChooser
from libtovid.cli import Command, Pipe
from libtovid.util import imagemagick_fonts
import ImageTk
import base64
 
class FontChooser (Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.pack()
        self.fontimg = PhotoImage()
        self.fontname = StringVar()
        self.fontname.set('helvetica')
        self.fontsize = IntVar()
        self.colour = 'black'
        self.font_colour = ''
        self.fontsize.set(20)
        self.fontlist = Listbox(self, width=40)
        self.preview = Label(self, image=None, height=6)
        for font in self.get_fonts():
            self.fontlist.insert(END, font)
        self.fontlist.bind('<Button-1>', self.select)
        self.colour_button = Button(self, text="Font Color", command=self.askColour)
        self.number = Scale(self, from_=0, to=64,
                                   tickinterval=0,
                                   orient='horizontal', variable=self.fontsize, label='Font Size')
        self.number.bind('<ButtonRelease-1>', self.makePreview)
#        self.number.bind('<Left>', self.makePreview)
#        self.number.bind('<Right>', self.makePreview)
        self.colour_button.pack(pady=5)
        self.number.pack(pady=5)
        self.fontlist.pack(pady=5)
        self.preview.pack(fill=BOTH, expand=1)
        self.makePreview()

 
    def select(self, event):
        self.index = self.fontlist.nearest(event.y)
        self.fontname.set(self.fontlist.get(self.index))
        #self.font_colour = self.colour
        self.makePreview()
 
    def get_fonts(self):
        """Return a list of font names available in ImageMagick."""
        return imagemagick_fonts()
    

    def makePreview(self, event=None):
        """Make a BitmapImage with selected font and display in the label"""
        self.fontimg.__del__()
        self.setOptions()
        self.im.run(capture=True)
        self.fontdata = base64.b64encode(self.im.get_output())
        self.fontimg = PhotoImage(data=self.fontdata)
        self.preview.configure(image=self.fontimg, height=self.fontimg.height())

    def askColour(self):
        self.cstr, self.colour = tkColorChooser.askcolor(title='pick a colour')
        self.makePreview()
     
    def setOptions(self):
        """Set options for imagemagick command"""
        self.im = Command('convert', '-size',  '255x150', "xc:#EFEFEF", '-font')
        self.im.add(self.fontname.get())
        self.im.add('-fill', self.colour)
        self.im.add('-pointsize', self.fontsize.get())
        im_opts = "-gravity center -annotate +0+0 'My title'"
        options = shlex.split(im_opts)
        for opt in options:
            self.im.add(opt)
        self.im.add('gif:-')

if __name__ == '__main__':
    root = Tk()
    chooser = FontChooser(root)
    root.mainloop()
